package com.example.exception.exception;

import com.example.exception.vo.MsgVO;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object handler(HttpServletRequest request, Exception e) throws Exception{
        if(isAjax(request)){
            return MsgVO.failure(e.getMessage());
        }else {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("message",e.getMessage());
            modelAndView.addObject("url",request.getRequestURL());
            modelAndView.setViewName("error");//html文件路径
            return modelAndView;
        }
    }

    public boolean isAjax(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null && "XMLHttpRequest".equals(request.getHeader("X-Requested-With")));
    }
}
